import {
  getProductName,
  networkConfigTypes,
} from '@/config/product';
import {
  setDeviceOnboardingDeploy,
  stopDeviceOnboarding,
} from '@/services/gizwitsSdk';
// eslint-disable-next-line no-unused-vars
import Base, {
  IBaseConfigNetworkInitProps,
  IConfigNetworkParam,
} from '../base/baseConfigNetwork';
import deviceListModel from '@/models/deviceList';
import language from '@/models/language';


export default class BTWifiConfig extends Base {
  softAPSSIDPrefixs?: string[];
  isStart = false
  constructor(
    props: IBaseConfigNetworkInitProps
  ) {
    console.log('BTWifiConfig constructor');
    super(props);
    this.type = networkConfigTypes.TNetworkConfigTypeBTWifi;
    if (props.productConfig && props.productConfig.btWifi) {
      this.configTips = props.productConfig.btWifi;
    }
  }

  async startConfig(params?: IConfigNetworkParam & { softAPSSIDPrefix: string }) {
    console.log('BT config', params);
    if (!params) {
      return {};
    }
    super.startConfig(params);
    this.isStart = true;
    const { wifiName, password, timeout, softAPSSIDPrefix } = params;
    const data = await setDeviceOnboardingDeploy({
      ssid: wifiName,
      key: password,
      mode: 3, // 3 是蓝牙单配
      timeout: timeout || 100,
      gagentTypes: [],
      ...(softAPSSIDPrefix
        ? { softAPSSIDPrefix }
        : { softAPSSIDPrefix: this.productConfig.softAPSSIDPrefix || '' }),
      isBind: false,
    });

    console.debug('setDeviceOnboardingDeploy', data);

    if (data.success) {
      const configDevice = data.data[0]

      // 30s 超时
      const startTime = Date.now();
      while (true) {
        const res = await deviceListModel.getDeviceList();
        console.debug('setDeviceOnboardingDeploy devices', res.data);
        
        const target = res.data?.find(item => item.mac.toLowerCase() === configDevice.mac.toLowerCase() && item.is_online);
        if (target) {
          // 修改默认名称
          const productName = getProductName(target.product_key, language.key);

          const mac_address = target.mac.substring(target.mac.length - 4)
          const name = `${productName || target.mac}-${mac_address}`
          deviceListModel.renameDevice({ device: target, name });
          break;
        }
        if (!this.isStart) {
          break;
        }
        if (Date.now() - startTime > 30000) {
          return {success: false, message: 'TIMEOUT'}
        }
        await new Promise(resolve => setTimeout(resolve, 2000));
      }
    }

    return data;
  }

  endConfig() {
    this.isStart = false;
    stopDeviceOnboarding();
  }
}
